import { ref, reactive, readonly, toRaw, watch, onUnmounted } from 'vue'

const state = reactive({
  ctrl: false,
  shift: false,
  alt: false
})

const preventDefaultSelectors = {}
const stopPropagationSelectors = {}

export function useKeyboard() {
  return readonly(state)
}

export function usePreventDefault(selector: string) {
  preventDefaultSelectors[selector] = true
  onUnmounted(() => delete preventDefaultSelectors[selector])
}

export function useStopPropagation(selector: string) {
  stopPropagationSelectors[selector] = true

  onUnmounted(() => delete stopPropagationSelectors[selector])
}

export function registerGlobalKeyboardEvent() {

  window.addEventListener('keydown', (ev: KeyboardEvent) => {
    const key = ev.key
    state.ctrl = 'Control' === key || ev.ctrlKey
    state.alt = 'Alt' === key || ev.altKey
    state.shift = 'Shift' === key || ev.shiftKey
  })

  window.addEventListener('keyup', (ev: KeyboardEvent) => {
    const key = ev.key
    if ('Control' === key) {
      state.ctrl = false
    }
    if ('Alt' === key) {
      state.alt = false
    }

    if ('Shift' === key) {
      state.shift = false
    }

  })
}